package com.scvtc.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;

/**
 * @Description: 文件上传
 * @Author: yiFei
 * @date: 2022/4/21 8:37
 */
public class ExportExcelUtil {

    private ExportExcelUtil() {

    }

    /**
     * 不带文件名字的
     *
     * @param exportParams 定义标题 sheet表民
     * @param clazz        类型
     * @param collection   数据
     * @param response     响应
     */
    public static void exportExcel(
            ExportParams exportParams,
            Class<?> clazz,
            Collection<?> collection,
            HttpServletResponse response) {
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, clazz, collection);
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setContentType("application/octet-stream");
            response.flushBuffer();
            sheets.write(out);
            sheets.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 带上传名字的 Excel
     *
     * @param exportParams 定义标题 sheet表民
     * @param clazz        类型
     * @param collection   数据
     * @param response     响应
     * @param fileName     文件名
     */
    public static void exportExcel(
            ExportParams exportParams,
            Class<?> clazz,
            Collection<?> collection,
            HttpServletResponse response, String fileName) {
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, clazz, collection);
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=".concat(URLEncoder.encode(fileName, "UTF-8")));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.flushBuffer();
            sheets.write(out);
//            sheets.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
